package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 登录Controller
 *
 * @author xiaoping
 * @create 2020/7/1 15:24
 * @since 1.0.0
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 通过登录token 获取用户信息
     * @param token
     * @return
     */
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        return redisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String ssoToken){
        if (!StringUtils.isEmpty(ssoToken)){
            //之前有人登陆过，浏览器留下了痕迹
            return "redirect:"+url+"?token="+ssoToken;
        }
        model.addAttribute("url", url);
        return  "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
                          @RequestParam("url") String url, HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //存入登录信息
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            //添加cookie
            Cookie ssoToken = new Cookie("sso_token", uuid);
            response.addCookie(ssoToken);
            return "redirect:"+url+"?token="+uuid;
        }

        //登录成功跳转,跳回到之前的页面
        return  "login";
    }

}
